#include <iostream>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
    // first存储的是坡度和，second存储节点总和
    typedef pair<int, int> PII;
    PII _findTilt(TreeNode *root)
    {
        if (!root)
            return {0, 0};
        PII t1 = _findTilt(root->left);
        PII t2 = _findTilt(root->right);
        int tilt = abs(t1.second - t2.second);
        return {t1.first + t2.first + tilt, t1.second + t2.second + root->val};
    }
    int findTilt(TreeNode *root)
    {
        // if(!root) return 0;
        // int t1 = findTilt(root->left);
        // int t2 = findTilt(root->right);
        // return t1+t2;
        int sum = 0;
        return _findTilt(root).first;
    }
};